<?php
namespace app\middleware;

class JWT
{
    protected $header=null;

    protected $payload=null;

    private $secret='jwtadmin';

    private $expires=3600;

    public function __construct($user=''){
        $this->initHeader();
        $this->initPayload($user);
    }

    private function initHeader(){
        $this->header['type']='JWT';
        $this->header['alg']="HS256";
    }

    private function initPayload($user){
        if($user=='' || $user==null){
            return false;
        }
        $this->payload['iss']='jwtadmin';
        $this->payload['sub']='admin';
        $this->payload['aud']=$user;
        $this->payload['exp']=time()+$this->expires;
        $this->payload['iat']=time();
    }

    private function initSecret(){
        $this->secret='jwtadmin';
    }

    public function base64en($value){
        $tmp_value=$value;
        if(is_array($value)){
          $tmp_value=serialize($value);
        }
        return base64_encode($tmp_value);
    }

    public function base64de($value){
        if(!is_string($value)){
            return false;
        }

        return unserialize(base64_decode($value));
    }

    public function signatures(){
        if($this->header == null || $this->payload == null){
            return false;
        }

        $this->initSecret();

        $base64_header=$this->base64en($this->header);
        $base64_payload=$this->base64en($this->payload);
        if($this->header['alg']=='HS256'){
            $sig=hash_hmac('sha256',$base64_header.$base64_payload,$this->secret);
        }

        return $base64_header.'.'.$base64_payload.'.'.$sig;
    }

    public function check($token) {
        $token_info=explode('.',$token);
        $token_header=$this->base64de($token_info[0]);
        $token_payload=$this->base64de($token_info[1]);
        $token_signature=$token_info[2];
        $this->header=$token_header;
        $this->payload=$token_payload;

        if($this->signatures()===$token){
            if($token_payload['exp'] < time()){
                //var_dump($token_payload['exp']);die;
                return false;
            }
            return $token_payload['aud'];
        }else{
            return false;
        }

        return false;
    }

}
